<template>
  <div class="wait-send-list-container">
    <div class="wait-send-list-main">
      <div class="wait-send-list-top"
           v-if="urlParamObj.name">
        <span>{{ urlParamObj.name }}</span>
        <span>({{ pagination.total }})</span>
      </div>
      <!-- 发送待办时工作流里面需要获取隐藏的input -->
      <div id="workflow_definition"
           style="display: none">
        <input type="hidden"
               id="process_desc_by" />
        <input type="hidden"
               id="process_xml" />
        <input type="hidden"
               id="readyObjectJSON" />
        <input type="hidden"
               id="workflow_data_flag"
               name="workflow_data_flag"
               value="WORKFLOW_SEEYON" />
        <input type="hidden"
               id="process_info" />
        <input type="hidden"
               id="process_subsetting" />
        <input type="hidden"
               id="moduleType"
               value="1" />
        <input type="hidden"
               id="workflow_newflow_input" />
        <input type="hidden"
               id="process_rulecontent" />
        <input type="hidden"
               id="workflow_node_peoples_input" />
        <input type="hidden"
               id="toReGo" />
        <input type="hidden"
               id="workflow_node_condition_input" />
      </div>
      <div :id="searchConditionContainerId"></div>
      <div class="wait-send-list-header">
        <CommonCounter v-if="selectedRowKeys.length"
                       :total="pagination.total"
                       :currentSelected="selectedRowKeys.length"
                       @cancelSelected="cancelSelected" />
        <div class="toolbar-container">
          <CommonToolbar :allToolBtns="allToolBtns"
                         @buttonClick="buttonClick"> </CommonToolbar>
        </div>
        <div class="search-part">
          <a-input-search :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                          style="width: 272px"
                          :allowClear="true"
                          @change="onInputSearchValueChange"
                          @search="onSearch" />
          <div class="condition-container">
            <SearchCondition :containerParentId="searchConditionContainerId"
                             :conditions="searchConditions"
                             @valueChange="conditionFilter"
                             @expandChange="expandChange"></SearchCondition>
          </div>
        </div>
      </div>
      <div class="wait-send-list-content">
        <div>
          <AVirtuallyTable :row-selection="{
            columnWidth: 60,
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange
          }"
                           ref="avirtuallyTable"
                           :rowKey="rowKey"
                           :pagination="true"
                           :loading="loading"
                           :localstorageKey="getLocalStorageKey"
                           :paginationOption="pagination"
                           size="small"
                           :bordered="false"
                           :columns="columns"
                           :openVirtuallyModel="true"
                           :dataSource="dataSource"
                           :rightClickMenus="rightClickMenus"
                           :titleRightMenus="titleRightMenus"
                           @paginationChange="handleTableChange"
                           @paginationShowSizeChange="paginationShowSizeChange"
                           @rowDelayClick="rowClick"
                           @rowDoubleClick="rowDoubleClick">
            <!-- 分类插槽 -->
            <span slot="categoryLabel"
                  slot-scope="{ text, record }">
              <CategoryLabel :text="text"
                             :urlParams="urlParamObj"
                             :slotData="record"
                             :isWaitList="true">
              </CategoryLabel>
            </span>
            <!-- 状态插槽 -->
            <span slot="subState"
                  slot-scope="{ text }"
                  :title="subStateName[text]">
              {{ subStateName[text] }}
            </span>
            <!-- 标题插槽 -->
            <span slot="subject"
                  slot-scope="{ record }">
              <subjectTitle :slotData="record"
                            :urlParams="urlParamObj"> </subjectTitle>
            </span>
          </AVirtuallyTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  window._wfctxPath = window._ctxPath;
  import CommonToolbar from '../../components/common-toolbar/index';
  import CommonCounter from '../../components/common-counter/index';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import subjectTitle from '../track-list/components/subject-title.vue';
  import CategoryLabel from '../track-list/components/category-label.vue';
  import collaboration from '../../utils/collaboration.js';
  import smartCodeMixin from '../../mixins/smart-code-mixin';
  import {getParams, loadComponentsThemeDefaultCSS, toastForward} from '../../utils';
  import { formatRequestDataToJSON, loadExtendResource } from '@/utils/api';
  import * as Fiber from 'fiber';
  export default {
    name: 'WaitSendList',
    components: {
      CommonToolbar,
      CommonCounter,
      SearchCondition,
      AVirtuallyTable,
      subjectTitle,
      CategoryLabel
    },
    mixins: [smartCodeMixin],
    data() {
      return {
        fromType: 0, //0是菜单和磁贴， 1是栏目更多
        allToolBtns: [],
        showCounter: false,
        loading: true,
        canDel: true,
        rowKey: 'id',
        canForward: true,
        searchConditionContainerId: 'search-condition-container-parent',
        searchConditions: [],
        dataSource: [],
        condition: null,
        columns: [],
        selectedRowKeys: [],
        selectedRows: [],
        urlParamObj: {},
        titleRightMenus: {
          asc: true,
          desc: true,
          freeze: true,
          fieldset: true
        },
        pagination: {
          page: 1,
          // pageSize: 20,
          total: 0
          // pageSizeOptions: ['10', '20', '30', '40', '50'],
          // showTotal: (total) => `${this.$i18n('orgrole.total_items', total)}`,
          // showSizeChanger: true
        },
        searchValue: ''
      };
    },
    created() {
      this.subStateName = {
        1: this.$i18n('collaboration.substate.1.label'),
        3: this.$i18n('collaboration.substate.3.label'),
        2: this.$i18n('collaboration.substate.new.2.label'),
        16: this.$i18n('collaboration.substate.new.2.label'),
        18: this.$i18n('collaboration.substate.new.2.label')
      };
      this.urlParamObj = getParams(window.location.search);
      this.fromType = this.urlParamObj.pageKey == 'LIST_WAIT_SEND_SECTION' ? 1 : 0;
      this.rowKey = this.fromType == 0 ? 'affairId' : 'id';
      this.urlParamObj.name
        ? (this.urlParamObj.name = window.decodeURIComponent(this.urlParamObj.name))
        : '';
      this.getTableHeader();
      this.getTableData();
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    mounted() {
      window.onstorage = (e) => {
        if (e.key == 'sendEvent') {
          this.getTableData();
        }
      };
    },
    computed: {
      getLocalStorageKey() {
        return window._currentUser.id + this.urlParamObj.pageKey||'WAIT_SEND_LIST';
      }
    },
    methods: {
      initToolbar() {
        const submenu = [];
        //转发协同和转发邮件需要由插件控制
        const hasNewColl = window._hasResource('F01_newColl');
        const hasMailCreate = window._hasResource('F12_mailcreate');
        const emailShow = window._hasPlugin('webmail');
        if (hasNewColl && this.canForward) {
          submenu.push({
            //转发协同
            id: 'transmitCol',
            name: this.$i18n('common.toolbar.transmit.col.label')
          });
        }
        if (hasMailCreate && emailShow && this.canForward) {
          submenu.push({
            //转发邮件
            id: 'transmitMail',
            name: this.$i18n('common.toolbar.transmit.mail.label')
          });
        }
        this.allToolBtns.push({
          id: 'send',
          name: this.$i18n('common.toolbar.send.label') //发送
        });
        this.allToolBtns.push({
          id: 'edit',
          name: this.$i18n('common.operate.edit') //编辑
        });
        if (this.fromType == 0) {
          if ((hasNewColl || hasMailCreate) && this.canForward) {
            this.allToolBtns.push({
              id: 'transmit',
              name: this.$i18n('common.toolbar.transmit.label'), //转发
              subMenu: submenu
            });
          }
          if (this.canDel) {
            this.allToolBtns.push({
              id: 'delete',
              name: this.$i18n('common.toolbar.delete.label') //删除
            });
          }
        } else {
          if (this.isHaveSmartCodePermission()) {
            this.allToolBtns.push(this.smartCodeBtnInfo);
          }
        }
      },
      getTableHeader() {
        const headerParams = {
          key: this.urlParamObj.pageKey || 'LIST_WAIT_SEND',
          // 终端 0 pc 1 mobile （取值参照PlatformType）
          platform: 0,
          // 业务传参，由业务决定（后续可在元数据拦截器中获取到）
          arguments: {
            fragmentId: this.urlParamObj.fragmentId || '',
            ordinal: this.urlParamObj.ordinal || '',
            bigTitleIndex: this.urlParamObj.bigTitleIndex || '',
            userId: window._currentUser.id
          }
        };
        const url = `${window._ctxPath}/rest/global/metadata/list`;
        window.axios.post(url, headerParams).then((res) => {
          if (res.data.code === 0) {
            const resData = res.data.data;
            const colunmsArr = [];
            loadExtendResource(resData.extra?.extendResources);
            resData?.tableColumns.forEach((item) => {
              if (item.type != 'CHECKBOX') {
                let column = {
                  title: item.title,
                  width: item.width,
                  dataIndex: item.key,
                  ellipsis: true,
                  key: item.key,
                  fixed: false,
                  dropdownMenus: {
                    asc: true,
                    desc: true,
                    freeze: true,
                    fieldset: true
                  }
                };
                if (item.key == 'categoryLabel') {
                  column.scopedSlots = { customRender: 'categoryLabel' };
                } else if (item.key == 'subState') {
                  column.scopedSlots = { customRender: 'subState' };
                } else if (item.key == 'subject') {
                  column.scopedSlots = { customRender: 'subject' };
                }
                column.customCell = () => {
                  return {
                    style: {
                      padding: '0 8px',
                      height: '38px',
                      cursor: 'pointer'
                    }
                  };
                };
                colunmsArr.push(column);
              }
            });
            this.searchConditions = resData.searchConditions.filter((item) => item.key !== 'subject');
            this.columns = colunmsArr;
            this.server2LocalTime = resData.globalParam.server2LocalTime; //服务器时间和本地时间差异
            this.secretLevelEnable = resData.globalParam.secretLevelEnable; //密级
            this.canDel = resData.globalParam.canDel; //能否删除
            this.canForward = resData.globalParam.newColNodePolicy.forward; //能否转发
          }
          this.initToolbar();
        });
      },
      getTableData() {
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
        this.loading = true;
        this.selectedRowKeys = [];
        const {
          fragmentId = '',
          ordinal = '',
          bigTitleIndex = '',
          textfield = ''
        } = this.urlParamObj;
        let getDataParam = {
          templeteIds: textfield,
          subject: this.searchValue,
          ...this.condition
        };
        if (this.fromType == 1) {
          getDataParam = {
            fragmentId,
            ordinal,
            bigTitleIndex,
            state: '1',
            isTrack: 'false',
            condition: 'subject',
            textfield: this.searchValue,
            ...getDataParam
          };
        }
        if (this.condition) {
          getDataParam.condition = 'comQuery';
          delete getDataParam.textfield;
        }
        const sendParams = [
          { page: this.pagination.page, size: this.pagination.pageSize },
          getDataParam
        ];
        let managerName = 'colManager';
        let managerMethod = 'getWaitSendList';
        //更多进来
        if (this.fromType == 1) {
          managerName = 'pendingManager';
          managerMethod = 'getMoreList4SectionContion';
        }
        this.ajaxDo(managerName, managerMethod, sendParams)
          .then((data, err) => {
            this.loading = false;
            console.log(err, 'err');
            console.log(data, 'resultresult');
            const result = data.data;
            if (result) {
              this.pagination.total = result.total;
              this.dataSource = result.data;
            }
            window.parent.refreshMenuList && window.parent.refreshMenuList();
          })
          .catch((err) => {
            this.loading = false;
            console.log(err);
          });
      },
      conditionFilter(condition) {
        this.pagination.page = 1;
        //重要程度，状态
        const enumKeys = [
          'importLevel',
          'importantLevel',
          'importantLevelList',
          'subState',
          'subStateList'
        ];
        Object.keys(condition).forEach((key) => {
          if (enumKeys.includes(key)) {
            condition[key] = condition[key].join(',');
          }
        });
        //创建时间
        if (condition.createDate) {
          condition.createDate = condition.createDate.startDate + '#' + condition.createDate.endDate;
        }
        this.condition = condition;
        this.getTableData();
      },
      expandChange(isExpanded) {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.resizeTable();
        });
        console.log(this.$refs.avirtuallyTable.resize);
        console.log(isExpanded, 'isExpanded');
      },
      //点击穿透
      rowClick(row) {
        const app = row.applicationCategoryKey;
        const subApp = row.applicationSubCategoryKey;
        const affairId = row.affairId || row.id;
        let url = '';
        // const url;
        if (app == 4) {
          if (subApp == 19 || subApp == 20 || subApp == 21) {
            url =
              window._ctxPath +
              '/edocController.do?method=detailIFrame&from=listWaitSend&affairId=' +
              affairId;
          } else if (subApp == 1 || subApp == 2 || subApp == 3 || subApp == 4) {
            url =
              window._ctxPath +
              '/govdoc/govdoc.do?method=summary&openFrom=listWaitSend&affairId=' +
              affairId;
          }
        } else {
          url =
            window._ctxPath +
            '/collaboration/collaboration.do?method=summary&openFrom=listWaitSend&affairId=' +
            affairId +
            '&showTab=true';
        }

        if (url.indexOf('edoc') == -1 && url.indexOf('govdoc') == -1) {
          url += '&showTab=true';
        }
        this.showSummayDialogByURL(url);
      },
      //双击编辑
      rowDoubleClick(row) {
        const affairId = row.id || row.affairId;
        const summaryId = row.objectId || row.summaryId;
        const subState = row.subState;
        const app = row.applicationCategoryKey;
        const subApp = row.applicationSubCategoryKey;
        const templateId = row.templateId;
        this.edit(affairId, summaryId, subState, app, subApp, templateId);
      },
      //发送
      sendWaitItem() {
        if (this.selectedRowKeys.length > 1) {
          Fiber.message.warning($.i18n('collaboration.moreWaitSend.selectOneSend'));
          return;
        } else if (this.selectedRowKeys.length < 1) {
          Fiber.message.warning($.i18n('collaboration.moreWaitSend.selectSend'));
          return;
        } else {
          //发送
          let selecRow = this.selectedRows[0];
          const app = selecRow.applicationCategoryKey;
          const subApp = selecRow.applicationSubCategoryKey;
          const hasNewColl = window._hasResource('F01_newColl');
          const fawenNewQuickSend = window._hasResource('F20_fawenNewQuickSend');
          const newSend = window._hasResource('F20_newSendl');
          const newDengji = window._hasResource('F20_newDengji');
          const newSign = window._hasResource('F20_newSign');
          if (app == 1 && !hasNewColl && selecRow.templateId == 'null') {
            Fiber.message.warning($.i18n('collaboration.listWaitSend.noNewCol'));
            return false;
          } else if (app == 4) {
            if (subApp == 1 || subApp == 19) {
              //发文
              if (!fawenNewQuickSend && !newSend) {
                Fiber.message.warning($.i18n('alert_not_edoccreate'));
                return false;
              }
            } else if (subApp == 2 || subApp == 20) {
              //收文
              if (!newDengji) {
                Fiber.message.warning($.i18n('alert_not_edocregister'));
                return false;
              }
            } else if (subApp == 3 || subApp == 21) {
              //签报
              if (!newSign) {
                Fiber.message.warning($.i18n('alert_not_edocregister'));
                return false;
              }
            }
          }
          this.sendItem(selecRow);
        }
      },
      //编辑
      editWaitItem() {
        if (this.selectedRowKeys.length > 1) {
          Fiber.message.warning($.i18n('collaboration.grid.alert.selectOneEdit'));
          return;
        } else if (this.selectedRowKeys.length < 1) {
          Fiber.message.warning($.i18n('collaboration.grid.alert.selectEdit'));
          return;
        } else {
          //更多和菜单进来的数据有差异
          const affairId = this.selectedRows[0].id || this.selectedRows[0].affairId;
          const summaryId = this.selectedRows[0].objectId || this.selectedRows[0].summaryId;
          const subState = this.selectedRows[0].subState;
          const app = this.selectedRows[0].applicationCategoryKey;
          const subApp = this.selectedRows[0].applicationSubCategoryKey;
          const templateId = this.selectedRows[0].templateId;
          this.edit(affairId, summaryId, subState, app, subApp, templateId);
        }
      },
      edit(affairId, summaryId, subState, app, subApp, templateId) {
        const hasNewColl = window._hasResource('F01_newColl');
        if (app == 1 && !hasNewColl && templateId == 'null') {
          Fiber.message.warning($.i18n('collaboration.listWaitSend.noNewCol'));
          return false;
        }
        if (app == 4) {
          if (subApp == 1 || subApp == 19) {
            //发文
            this.checkIsRole(affairId, summaryId, subState, app, subApp, templateId, 401);
          } else if (subApp == 2 || subApp == 20) {
            //收文
            this.checkIsRole(affairId, summaryId, subState, app, subApp, templateId, 402);
          } else if (subApp == 3 || subApp == 21) {
            //签报
            this.checkIsRole(affairId, summaryId, subState, app, subApp, templateId, 403);
          }
        } else {
          this.editCol(affairId, summaryId, subState);
        }
      },
      //删除
      deleteWaitItem() {
        if (this.selectedRowKeys.length < 1) {
          Fiber.message.warning($.i18n('collaboration.grid.selectDelete'));
          return;
        }
        const SummaryIds = [];
        const affairIds = [];
        this.selectedRows.forEach((row) => {
          SummaryIds.push(row.summaryId);
          affairIds.push(row.affairId);
        });
        //js事件接口
        let idMap = {
          summaryID: SummaryIds,
          affairID: affairIds
        };
        console.log('$.ctp.trigger', 'beforeWaitSendDelete', idMap);
        var sendDevelop = $.ctp.trigger('beforeWaitSendDelete', idMap);
        if (!sendDevelop) {
          // Fiber.message.warning($.i18n('collaboration.page.js.third.error.alert.js'));
          return;
        }
        this.deleteItems(affairIds);
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRows = selectedRows;
      },
      onInputSearchValueChange(e) {
        this.searchValue = e.target.value;
      },
      onSearch(e) {
        this.searchValue = e;
        this.pagination.page = 1;
        this.getTableData();
      },
      cancelSelected() {
        this.showCounter = false;
        // this.selectedRows = [];
        // this.selectedRowKeys = [];
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
      },
      //按钮点击事件
      buttonClick(buttonKey) {
        switch (buttonKey) {
          case 'edit':
            this.editWaitItem();
            break;
          case 'delete':
            this.deleteWaitItem();
            break;
          case 'send':
            this.sendWaitItem();
            break;
          case 'transmitCol':
            this.transmitColFromGrid();
            break;
          case 'transmitMail':
            this.transmitMail('listWaitSend');
            break;
          case 'smartCodeScan': // 扫一扫
            this.showSmartCode && this.showSmartCode();
            break;
        }
      },
      handleTableChange(page, pageSize) {
        this.pagination.page = page;
        this.pagination.pageSize = pageSize;
        this.getTableData();
      },
      paginationShowSizeChange(current, size) {
        console.log(current, size);
        this.pagination.page = 1;
        this.pagination.pageSize = size;
        this.getTableData();
      },
      //转发协同
      transmitColFromGrid() {
        const selectLength = this.selectedRowKeys.length;
        const sendData = [];
        if (selectLength === 0) {
          //请选择要转发的协同
          Fiber.message.warning($.i18n('collaboration.grid.alert.transmitCol'));
          return;
        } else if (selectLength > 1 && this.SecretLevelEnable) {
          Fiber.message.warning($.i18n('collabration.secret.transfer.num.limit'));
          return;
        } else if (selectLength > 20) {
          //只能选择20项协同进行转发
          Fiber.message.warning($.i18n('collaboration.grid.alert.transmitColOnly20'));
          return;
        }
        console.log('$.ctp.trigger', 'beforeTransmitCol', this.selectedRowKeys);
        const sendDevelop = $.ctp.trigger('beforeTransmitCol', this.selectedRowKeys);
        if (!sendDevelop) {
          return;
        }
        for (let i = 0; i < selectLength; i++) {
          const selectedObj = this.selectedRows[i];
          const app = selectedObj.applicationCategoryKey || selectedObj.app;
          if (app == 19 || app == 20 || app == 21) {
            //公文不允许转发协同
            Fiber.message.warning($.i18n('collaboration.grid.alert.DocumentNotForwardCol'));
            return;
          } else if (app == '32') {
            //信息报送不允许转发协同
            Fiber.message.warning($.i18n('collaboration.grid.alert.InfoNotForwardCol'));
            return;
          } else if (app == 81) {
            //模板审批不允许转发协同
            Fiber.message.warning($.i18n('collaboration.grid.alert.InfoNotTemplateApproveColl'));
            return;
          } else if (app == 4) {
            Fiber.message.warning($.i18n('govdoc.grid.alert.DocumentNotForwardCol'));
            return;
          } else {
            const summaryId = selectedObj.summaryId || selectedObj.objectId;
            const affairId = selectedObj.affairId || selectedObj.id;
            const isSuperNode = selectedObj.superNode;

            if (selectedObj.templeteId) {
              //var r = cm.checkTemplateCanUse(selectBox[i].templeteId);
              const result = window.callBackendMethod(
                'colManager',
                'isTemplateDeleted',
                selectedObj.templeteId
              );
              // const result = await this.getAsyncData(
              //   'colManager',
              //   'isTemplateDeleted',
              //   selectedObj.templeteId
              // );
              if (result == '1') {
                //被删除
                Fiber.message.warning($.i18n('template.coll.not.ues.js', selectedObj.subject));
                return;
              }
            }
            if (isSuperNode === true) {
              Fiber.message.warning($.i18n('workflow.supernode.msg.not_transmit.js'));
              return;
            }
            sendData.push({
              summaryId,
              affairId
            });
          }
        }
        this.transmitColById(sendData);
      },

      transmitColById(data) {
        let checkPermissionData = '';
        let doForwardData = '';

        data.forEach((item) => {
          doForwardData += item.summaryId + '_' + item.affairId + ',';
          checkPermissionData += item.affairId + ',';
        });

        const result = window.callBackendMethod(
          'colManager',
          'checkForwardPermission',
          checkPermissionData
        );
        // const result = await this.getAsyncData(
        //   'colManager',
        //   'checkForwardPermission',
        //   checkPermissionData
        // );
        if (result && result instanceof Array && result.length > 0) {
          //以下协同不能转发，请重新选择
          toastForward.call(this, result);
          return;
        }
        const dialog = $.dialog({
          id: 'showForwardDialog',
          height: '400',
          width: '550',
          url:
            window._ctxPath +
            '/collaboration/collaboration.do?method=showForward&data=' +
            doForwardData,
          title: $.i18n('common.toolbar.transmit.col.label'),
          targetWindow: window.getCtpTop(),
          isClear: false,
          transParams: {
            commentContent: ''
          },
          buttons: [
            {
              id: 'okButton',
              text: $.i18n('common.button.ok.label'),
              btnType: 1,
              handler: () => {
                dialog.getReturnValue();
              },
              OKFN: () => {
                window.parent.refreshMenuList && window.parent.refreshMenuList();
                this.getTableData();
                dialog.close();
              }
            },
            {
              id: 'cancelButton',
              text: $.i18n('common.button.cancel.label'),
              handler: () => {
                dialog.close();
              }
            }
          ]
        });
      },
      transmitMail() {
        const emailShow = window._hasPlugin('webmail');
        if (emailShow) {
          //需要判断是否只勾选了一项，并给出相应的提示
          // var selectBox =grid.grid.getSelectRows();
          const selectedLength = this.selectedRowKeys.length;
          if (selectedLength === 0) {
            //请选择要转发的协同!
            Fiber.message.warning($.i18n('collaboration.grid.alert.transmitCol'));
            return;
          } else if (selectedLength > 1) {
            //只能选择一项协同进行转发
            Fiber.message.warning($.i18n('collaboration.grid.alert.transmitColOnlyOne'));
            return;
          }
          const selectedObj = this.selectedRows[0];
          const app = selectedObj.applicationCategoryKey || selectedObj.app;
          if (app == '19' || app == '20' || app == '21' || app == '4') {
            //公文不允许转发协同
            Fiber.message.warning($.i18n('collaboration.grid.alert.DocumentNotForwardEmail'));
            return;
          } else if (app == '32') {
            //信息报送不允许转发邮件
            Fiber.message.warning($.i18n('collaboration.grid.alert.InfoNotForwardEmail'));
            return;
          } else if (app == '81') {
            //协同模板不允许转发邮件
            Fiber.message.warning($.i18n('collaboration.grid.alert.InfoNotTemplateApproveEmail'));
            return;
          }
          // }

          let summaryId, affairId, isSuperNode;
          summaryId = selectedObj.summaryId || selectedObj.objectId;
          affairId = selectedObj.affairId || selectedObj.id;
          isSuperNode = selectedObj.superNode;
          // const canTrans = await this.getAsyncData(
          //   'secretAjaxManager',
          //   'canTransSecretLevel',
          //   summaryId
          // );

          const canTrans = window.callBackendMethod(
            'secretAjaxManager',
            'canTransSecretLevel',
            summaryId
          );
          if (canTrans == false) {
            Fiber.message.warning($.i18n('collaboration.grid.alert.noTransSecretData'));
            return;
          }
          // const result = await this.getAsyncData('colManager', 'checkForwardPermission', affairId);
          const result = window.callBackendMethod('colManager', 'checkForwardPermission', affairId);
          if (result && result instanceof Array && result.length > 0) {
            //以下协同不能转发，请重新选择
            toastForward.call(this, result);
            return;
          }

          if (isSuperNode === true) {
            Fiber.message.warning($.i18n('workflow.supernode.msg.not_transmit.js'));
            return;
          }
          //跳转门户菜单，需要确认资源
          const params = {};
          params.title = $.i18n('common.toolbar.transmit.mail.label');
          if (window.getCtpTop() && window.getCtpTop().showMenu) {
            window
              .getCtpTop()
              .showMenu(
                window._ctxPath +
                  '/collaboration/collaboration.do?method=forwordMail&summaryId=' +
                  summaryId +
                  '&affairId=' +
                  affairId,
                null,
                null,
                null,
                params
              );
          } else {
            window.showMenu(
              window._ctxPath +
                '/collaboration/collaboration.do?method=forwordMail&summaryId=' +
                summaryId +
                '&affairId=' +
                affairId,
              null,
              null,
              null,
              params
            );
          }
        }
      },
      //判断是否有收文、发文、签报权限
      checkIsRole(affairId, summaryId, subState, app, subApp, templateId, moduleType) {
        this.ajaxDo('edocManager', 'checkCreateRoleAuth', ['' + moduleType]).then((data) => {
          var backBoxToEdit = false;
          //退回和指定退回的数据在待发中编辑的时候不能调用模板
          if (subState == 2 || subState == 16 || subState == 18) {
            backBoxToEdit = true;
          }
          const result = data.data;
          if (result != '') {
            if (moduleType == '401') {
              Fiber.message.warning($.i18n('alert_not_edoccreate'));
            } else if (moduleType == '402') {
              Fiber.message.warning($.i18n('alert_not_edocregister'));
            } else {
              Fiber.message.warning($.i18n('alert_not_edocregister'));
            }
            return;
          } else {
            if (app == 4) {
              var url = '';
              if (subApp == 1) {
                //新公文-发文
                url =
                  window._ctxPath +
                  '/govdoc/govdoc.do?method=newGovdoc&summaryId=' +
                  summaryId +
                  '&affairId=' +
                  affairId +
                  '&from=waitSend&sub_app=1';
              } else if (subApp == 2) {
                //新公文-收文
                url =
                  window._ctxPath +
                  '/govdoc/govdoc.do?method=newGovdoc&summaryId=' +
                  summaryId +
                  '&affairId=' +
                  affairId +
                  '&from=waitSend&sub_app=2';
              } else if (subApp == 3) {
                //新公文-签报
                url =
                  window._ctxPath +
                  '/govdoc/govdoc.do?method=newGovdoc&summaryId=' +
                  summaryId +
                  '&affairId=' +
                  affairId +
                  '&from=waitSend&sub_app=3';
              } else if (subApp == 19) {
                //老公文-发文
                url =
                  window._ctxPath +
                  '/edocController.do?method=entryManager&entry=sendManager&toFrom=newEdoc&from=newEdoc&summaryId=' +
                  summaryId +
                  '&edocType=0&affairId=' +
                  affairId +
                  '&isSendBackBox=false&backBoxToEdit=' +
                  backBoxToEdit +
                  window.CsrfGuard.getUrlSurffix();
              } else if (subApp == 20) {
                //老公文-收文
                url =
                  window._ctxPath +
                  '/edocController.do?method=entryManager&entry=recManager&recListType=listDistribute&toFrom=newEdoc&listType=newEdoc&from=newEdoc&summaryId=' +
                  summaryId +
                  '&edocType=1&affairId=' +
                  affairId +
                  '&isSendBackBox=false&backBoxToEdit=' +
                  backBoxToEdit +
                  window.CsrfGuard.getUrlSurffix();
              } else if (subApp == 21) {
                //老公文-签报
                url =
                  window._ctxPath +
                  '/edocController.do?method=entryManager&entry=signReport&toFrom=newEdoc&from=newEdoc&summaryId=' +
                  summaryId +
                  '&edocType=2&affairId=' +
                  affairId +
                  '&isSendBackBox=false&backBoxToEdit=' +
                  backBoxToEdit +
                  window.CsrfGuard.getUrlSurffix();
              }
              if (subApp == 1 || subApp == 2 || subApp == 3) {
                window.openCtpWindow({ url: url, id: affairId });
              } else if (subApp == 19 || subApp == 20 || subApp == 21) {
                location.href = url + '&toPendingList=true';
              }
            } else {
              this.editCol(affairId, summaryId, subState);
            }
          }
        });
      },
      //检查模版是否可用
      checkTemplateCanUse(templateId) {
        return new Promise((resolve) => {
          this.ajaxDo('colManager', 'checkTemplateCanUse', [templateId]).then((result) => {
            if (result.data.flag == 'cannot') {
              resolve(false);
            } else {
              resolve(true);
            }
          });
        });
      },
      //发送
      sendItem(row) {
        const affairId = row.id || row.affairId;
        const summaryId = row.objectId || row.summaryId;
        const app = row.applicationCategoryKey;
        //检查流程期限是不是比当前日期早
        const deadlineDatetime = row.processDatetime;
        if (typeof deadlineDatetime != 'undefined') {
          let nowDatetime = new Date();
          //来自后端数据
          if (
            deadlineDatetime &&
            nowDatetime.getTime() + this.server2LocalTime >
              new Date(deadlineDatetime.replace(/-/g, '/')).getTime()
          ) {
            Fiber.message.warning($.i18n('collaboration.deadline.sysAlert'));
            return;
          }
        }
        if (app == 4) {
          //老公文的直接发送
          Fiber.message.warning($.i18n('govdoc.send.alert.isquicksend'));
          return;
        } else {
          //其他模块的直接发送
          //查询processId
          this.ajaxDo('colManager', 'getSummaryById', summaryId).then(async (result) => {
            const { processId, caseId, bodyType, newflowType } = result.data;
            let templeteId = result.data.templeteId;
            if (templeteId != '' && row.subState != '16' && newflowType != '2') {
              let canUse = await this.checkTemplateCanUse(templeteId);
              if (!canUse) {
                Fiber.message.warning($.i18n('template.cannot.use'));
                return;
              }
            } else {
              templeteId = '';
            }
            this.sendFromWaitSendList(bodyType, processId, templeteId, summaryId, caseId, affairId);
            window.closeOpenMultyWindow(affairId, false);
          });
        }
      },
      //待发列表发送 抽取方法
      sendFromWaitSendList(bodyType, processId, templeteId, summaryId, caseId, affairId) {
        if (bodyType == '20') {
          //表单流程请双击进入新建页面进行发送
          Fiber.message.warning($.i18n('collaboration.grid.alert.dclickSendFrom'));
          return;
        }
        if (!$.content) {
          $.content = {
            callback: {
              workflowNew: () => {
                const args = `CSRFTOKEN&_json_params=${JSON.stringify({
                  affairId,
                  summaryId,
                  workflow_node_peoples_input: $('#workflow_node_peoples_input', window.document)[0]
                    .value,
                  workflow_node_condition_input: $(
                    '#workflow_node_condition_input',
                    window.document
                  )[0].value,
                  toReGo: $('#toReGo', window.document)[0].value,
                  workflow_newflow_input: $('#workflow_newflow_input', window.document)[0].value
                })}`;
                let url = '';
                const bpmMenuFlag = parent.bpmMenuFlag;
                if (bpmMenuFlag == true) {
                  document.getElementById('bpmMenuFlag').value = '1';
                  url = `${window._ctxPath}/collaboration/collaboration.do?method=sendImmediate`;
                } else {
                  url = `${window._ctxPath}/collaboration/collaboration.do?method=sendImmediate`;
                }
                window.axios
                  .post(url, args, {
                    headers: {
                      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                    }
                  })
                  .then((result) => {
                    if (bpmMenuFlag == true) {
                      let resultJSON = null;
                      if (result && typeof result === 'string') {
                        resultJSON = $.parseJSON(args);
                      }
                      if (resultJSON && resultJSON.resourceCode != null && parent.clickMenu) {
                        parent.clickMenu(resultJSON.resourceCode); //跳转
                        window.setMenuListHighlight4resourceCode(resultJSON.resourceCode);
                      }
                    } else {
                      this.getTableData();
                    }
                  })
                  .catch((err) => {
                    console.log(err);
                  });
              }
            }
          };
        }
        window.matchRequestToken = 'PC-' + summaryId + '-t-' + new Date().getTime();
        // let secretLevelValue = await this.getAsyncData(
        //   'secretAjaxManager',
        //   'getFileSecretLevel',
        //   summaryId
        // );
        let secretLevelValue = window.callBackendMethod(
          'secretAjaxManager',
          'getFileSecretLevel',
          summaryId
        );
        let options = {
          tWindow: window,
          workitemId: '-1',
          processTemplateId: '',
          processId: processId,
          activityId: 'start',
          currentUserId: window._currentUser.id,
          caseId: caseId,
          currentAccountId: window._currentUser.loginAccount,
          appName: 'collaboration',
          secretLevel: secretLevelValue
        };
        // var secretLevelValue = callBackendMethod("secretAjaxManager", "getFileSecretLevel", summaryId);
        if (templeteId) {
          //根据模板ID去查询出流程的Id,顺便判断权限问题
          // let sflag = await this.getAsyncData('colManager', 'getTemplateId', templeteId);
          var sflag = window.callBackendMethod('colManager', 'getTemplateId', templeteId);
          if (sflag.wflag == 'cannot') {
            Fiber.message.warning($.i18n('collaboration.send.fromSend.templeteDelete')); //模板已经被删除，或者您已经没有该模板的使用权限三
            return;
          } else if (sflag.wflag == 'noworkflow') {
            //协同没有流程,不能发送
            Fiber.message.warning($.i18n('collaboration.grid.alert.dclickSendFrom'));
            return;
          }
          if (sflag.wflag == 'isTextTemplate') {
            if (!processId) {
              Fiber.message.warning($.i18n('collaboration.grid.alert.dclickSendFrom'));
              return;
            }
            window.preSendOrHandleWorkflow(options);
          } else {
            processId = sflag.wflag;
            options.processTemplateId = processId;
            window.preSendOrHandleWorkflow(options);
          }
        } else if (processId) {
          //这个优先级应更高
          if (!processId || processId == '') {
            Fiber.message.warning($.i18n('collaboration.grid.alert.dclickSendFrom'));
            return;
          }
          window.preSendOrHandleWorkflow(options);
        } else {
          let newProcessId = '';
          if (!processId || processId == '') {
            newProcessId = window.callBackendMethod('colManager', 'getProcessId', summaryId);
            // newProcessId = this.getAsyncData('colManager', 'getProcessId', summaryId);
          }
          if (!newProcessId || newProcessId == '') {
            Fiber.message.warning($.i18n('collaboration.grid.alert.dclickSendFrom'));
            return;
          } else {
            Fiber.message.warning($.i18n('collaboration.waitSend.noProcessRefresh')); //请刷新列表后再发送!
            return;
          }
        }
      },
      //编辑打开新页面
      editCol(affairId, summaryId, subState) {
        var url =
          window._ctxPath +
          '/collaboration/collaboration.do?method=newColl&summaryId=' +
          summaryId +
          '&affairId=' +
          affairId +
          '&from=waitSend&subState=' +
          subState +
          '&showTab=true';
        var obj = {
          url: url,
          id: affairId
        };
        var a8Top = window.getA8Top();

        if (a8Top.isMultipleTabs) {
          a8Top.openCtpWindow(obj);
        } else {
          window.openCtpWindow(obj);
        }
      },
      //删除待发
      deleteItems(affairIds) {
        let deleteSubject = '';
        console.log('$.ctp.trigger', 'beforeDeleteColl');
        let sendDevelop = $.ctp.trigger('beforeDeleteColl');
        const rows = this.selectedRows;
        if (!sendDevelop) {
          return;
        }
        // let processIndex = 0;
        const secretBatchCheckParams = [];
        let row = {};
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          secretBatchCheckParams.push({
            processId: row.processId,
            affairId: row.affairId,
            summaryId: row.summaryId,
            subject: row.subject
          });
          window.closeOpenMultyWindow(row.affairId, false);
          // 指定回退状态状态不能删除
          if (row.subState == '16') {
            Fiber.message.warning($.i18n('collaboration.alert.CantModifyBecauseOfAppointStepBack'));
            row.checked = false;
            return;
          }
          // 当前节点设置不允许删除:
          if (!row.canReMove) {
            if (rows.length == 1) {
              //当前节点权限不可进行删除操作！
              Fiber.message.warning($.i18n('collaboration.alert.CantReMoveOne'));
              row.checked = false;
              return;
            } else {
              //根据当前节点权限以下流程不可删除！
              deleteSubject += '<br>&lt;' + window.escapeStringToHTML(row.subject) + '&gt;';
            }
          }
        }
        if (deleteSubject.length > 1) {
          Fiber.message.warning({
            content: (h) =>
              h('span', {
                domProps: {
                  innerHTML: $.i18n('collaboration.alert.CantReMove') + deleteSubject
                }
              })
          });
          // Fiber.message.warning($.i18n('collaboration.alert.CantReMove') + deleteSubject);
          row.checked = false;
          return;
        }
        $.confirm({
          // 该操作不能恢复，是否进行删除操作
          msg: $.i18n('collaboration.confirmDelete'),
          ok_fn: () => {
            const sendParams = {
              pageType: 'draft',
              affairIds: affairIds.join(','),
              fromMethod: 'listWaitSend'
            };
            this.ajaxDo('colManager', 'checkCanDelete', sendParams)
              .then((result) => {
                if (result.data == 'success') {
                    this.loading=true;
                    let callback = () => {
                        //关闭已经删除了事项打开的子页面
                        for (let j = 0; j < affairIds.length; j++) {
                            window.closeOpenMultyWindow(affairIds[j], false);
                        }
                        // 成功删除，并刷新列表
                        $.messageBox({
                            title: $.i18n('common.system.hint.label'),
                            type: 0,
                            msg: $.i18n('common.delete.success.label'),
                            imgType: 0,
                            ok_fn: () => {
                                this.getTableData();
                                this.loading = false;
                                // this.unlockWorkflow();
                            },
                            close_fn: () => {
                                this.loading = false;
                                // this.unlockWorkflow();
                            }
                        });
                    }
                  this.deleteAffairsAjax('draft', affairIds, callback)
                } else {
                  Fiber.message.warning(result.data);
                  // this.unlockWorkflow();
                }
              })
              .catch((error) => {
                Fiber.message.warning(error);
                // this.unlockWorkflow();
              });
          },
          cancel_fn: () => {
            // this.unlockWorkflow();
          }
        });
      },
      deleteAffairsAjax(from, affairIds, callback) {
          var idsStr = affairIds.join(',');
          var url = `${window._ctxPath}/rest/coll/deleteAffairs/${from}/${idsStr}`;
          window.axios.get(url).then((ret) => {
              if(ret.data.success == 'true'){
                  callback.call(this);
              }else{
                  $.alert(ret.data.msg);
              }
          });
      }, 
      ajaxDo(method, managerMethod, sendData) {
        const args = `managerMethod=${managerMethod}&arguments=${formatRequestDataToJSON(sendData)}`;
        const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=${method}&rnd=97448`;
        return window.axios.post(url, args, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          }
        });
      },
      getAsyncData(method, managerMethod, sendData) {
        return new Promise((resolve) => {
          this.ajaxDo(method, managerMethod, sendData).then((result) => {
            resolve(result.data);
          });
        });
      },
      getSmartCodeDecodeParam() {
        const { fragmentId, ordinal, bigTitleIndex } = this.urlParamObj;
        const obj = {
          fragmentId,
          ordinal,
          bigTitleIndex,
          state: '1',
          isTrack: false,
          ...this.condition
        };
        obj.openFrom = 'moreWaitSend';
        return obj;
      },
      // 智码扫码成功后回调
      smartCodeCallBack(data) {
        collaboration.smartCodeCallBack(data);
      },
      showSummayDialogByURL(url) {
        //公文、协同都是affairId，会议是Id
        var affairIdIndex = url.indexOf('affairId');
        var idIndex = url.indexOf('id');
        var id = '';
        if (affairIdIndex != -1) {
          id = window.getMultyWindowId('affairId', url);
          this.openWindow({ url: url, id: id });
        } else if (idIndex != -1) {
          id = window.getMultyWindowId('id', url);
          this.openWindow({ url: url, id: id });
        } else {
          this.openWindow({ url: url });
        }
      },
      openWindow(obj) {
        const url = obj.url;
        const a8Top = window.getA8Top();
        if (a8Top.isMultipleTabs && url.indexOf('showTab=true') != -1 && !this.isOcipSummary(obj)) {
          a8Top.openCtpWindow(obj);
        } else {
          window.openCtpWindow(obj);
        }
      },
      //ocip推送过来的数据，不走多页签
      isOcipSummary(obj) {
        if (window._hasPlugin('ocip')) {
          let url = obj.url;
          if (url.indexOf('method=summary&') != -1 && url.indexOf('showTab=true') != -1) {
            let params = url.split('&');

            for (let i = 0; i < params.length; i++) {
              if (params[i].indexOf('affairId=') == -1) {
                continue;
              }
              let affairIds = params[i].split('=');
              if (affairIds[0] == 'affairId' && affairIds[1]) {
                return window.callBackendMethod(
                  'ocipColManager',
                  'checkIsExchangeAffair',
                  affairIds[1]
                );
              }
            }
          }
        }
        return false;
      }
    }
  };
</script>

<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss">
  .wait-send-list-container {
    position: relative;
    height: 100%;
    .wait-send-list-main {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      display: flex;
      padding-left: 16px;
      flex-direction: column;
      background-color: #ffffff;

      .wait-send-list-top {
        padding: 12px 16px 0 0;
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }

      .wait-send-list-header {
        display: flex;
        padding: 12px 16px 12px 0;
        height: 54px;
        box-sizing: border-box;

        .toolbar-container {
          flex: 1;
          overflow: hidden;
        }
      }

      .search-part {
        // flex: 1;
        display: flex;
        justify-content: flex-end;
        overflow: hidden;
        margin-left: 100px;

        .condition-container {
          margin-left: 12px;
          display: flex;
        }
      }

      .wait-send-list-content {
        flex: 1;
        padding: 0;
        position: relative;
        overflow: hidden;
        > div {
          position: absolute;
          left: 0;
          top: 0;
          right: 0;
          bottom: 0;
        }
      }
    }
  }
</style>
